package bs.app.android;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class HttpConnection implements Connection {
	
	String url = "";
	public HttpURLConnection conn = null;
	public static final int CONNECTION_TIME_OUT = 30 * 1000;
	public static final int HTTP_OK = 200;
	public static final String GET = "GET";
	public HttpConnection(){
		
	}
	public HttpConnection(String url) {
		this.url = url;
		//System.out.println("URL="+url);
		try {
			URL aURL = new URL(url);
			conn = (HttpURLConnection) aURL.openConnection();	
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
	
	public DataInputStream openDataInputStream() {
		try{
//			URL aURL = new URL(url);
//			conn = (HttpURLConnection) aURL.openConnection();			
			conn.setConnectTimeout(CONNECTION_TIME_OUT);		
			conn.connect();
			//System.out.println("vao URL:="+url);
			return (DataInputStream)conn.getInputStream();
		}
		catch (IOException e) {
		}
		return null;
	}
	
	public InputStream openInputStream() {
		try{
//			URL aURL = new URL(url);
//			conn = (HttpURLConnection) aURL.openConnection();
			conn.setConnectTimeout(CONNECTION_TIME_OUT);			
			conn.connect();
			return conn.getInputStream();
		}
		catch (IOException e) {
		}
		return null;
	}

	public DataOutputStream openDataOutputStream() {
		//TODO: CODE HERE
		return null;
	}

	public OutputStream openOutputStream() {
		//TODO: CODE HERE
		return null;
	}
	
	public void close() throws IOException {
		if(conn != null)
			conn.disconnect();
	}

	public void setRequestProperty(String s1, String s2) {
		// TODO Auto-generated method stub
		if(conn != null)
			conn.setRequestProperty(s1, s2);
	}

	public int getResponseCode() {
		// TODO Auto-generated method stub
		try {
			if(conn !=null)
				return conn.getResponseCode();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}

	public int getHeaderFieldInt(String string, int i) {
		return 0;
	}

	public int getLength() {
		return conn.getContentLength();
	}

	public void setRequestMethod(String str) {
		try {
			if(conn != null)
				conn.setRequestMethod("GET");
		} catch (ProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
